package com.hcl.orm.core.dialect.handler;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.hcl.orm.core.annotation.DBType;
import com.hcl.orm.core.annotation.SqlCommandType;
import com.hcl.orm.core.dialect.SqlDefinition;
import com.hcl.orm.core.dialect.SqlMetadata;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author hucl
 * @projectName hcl-orm
 * @description: TODO
 * @date 2021/8/1115:12
 */
@Component
public class SimpleDialectHandler extends AbstractDialectHandler {
    public SimpleDialectHandler() {
        super("默认数据库方言处理器");
    }

    @Override
    protected boolean needHandled(SqlDefinition sqlDefinition) {
        return StrUtil.isEmpty(sqlDefinition.getRawSql());
    }

    @Override
    protected void doHandle(SqlDefinition sqlDefinition) {
        SqlMetadata metadata = sqlDefinition.getSelectedSqlMetadata();
        String sql = null;
        if (!StrUtil.isEmpty(metadata.getTableName()) &&
                StrUtil.isEmpty(metadata.getRawSql())) {
            if (SqlCommandType.INSERT.equals(metadata.getSqlCommandType())) {
                sql= StrUtil.format("INSERT INTO {} ({}) VALUES ({});"
                        ,metadata.getTableName(),"{}","{}");
            }
            if (SqlCommandType.UPDATE.equals(metadata.getSqlCommandType())) {
                sql= StrUtil.format("UPDATE {} SET {} WHERE {};"
                        ,metadata.getTableName(),"{}","{}");

            }
            if (SqlCommandType.DELETE.equals(metadata.getSqlCommandType())) {
                sql= StrUtil.format("DELETE FROM {} WHERE {};"
                        ,metadata.getTableName(),"{}");
            }
            if (SqlCommandType.SELECT.equals(metadata.getSqlCommandType())) {
                sql= StrUtil.format("SELECT * FROM {} WHERE {};"
                        ,metadata.getTableName(),"{}");

            }
            sqlDefinition.setDialectSql(sql.toString());
        }
    }

    @Override
    protected List<DBType> getTargetDB() {
        return ListUtil.toList(DBType.ALL);
    }
}
